'use client'

import { useState, useEffect, useMemo } from 'react'
import { format, parseISO, isWithinInterval, subDays } from 'date-fns'
import { zhCN } from 'date-fns/locale'
import { toast } from 'react-hot-toast'

interface ActionLog {
  deviceId: string
  deviceName: string
  actionType: string
  value: any
  status: 'SUCCESS' | 'FAILED'
  message?: string
  startTime: Date
  endTime: Date
  duration: number
}

interface HistoryRecord {
  id: string
  sceneId: string
  status: 'SUCCESS' | 'FAILED' | 'PARTIAL_SUCCESS'
  message: string | null
  startTime: Date
  endTime: Date
  duration: number
  actionLogs: ActionLog[]
  error: any
  createdAt: Date
  retryCount: number
  retryOf?: string
}

interface SceneHistoryProps {
  sceneId: string
  sceneName: string
}

interface FilterOptions {
  status: 'ALL' | 'SUCCESS' | 'FAILED' | 'PARTIAL_SUCCESS'
  timeRange: 'ALL' | 'TODAY' | 'WEEK' | 'MONTH'
  search: string
}

export default function SceneHistory({ sceneId, sceneName }: SceneHistoryProps) {
  const [history, setHistory] = useState<HistoryRecord[]>([])
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState('')
  const [filters, setFilters] = useState<FilterOptions>({
    status: 'ALL',
    timeRange: 'ALL',
    search: ''
  })
  const [page, setPage] = useState(1)
  const itemsPerPage = 10

  useEffect(() => {
    fetchHistory()
  }, [sceneId])

  const fetchHistory = async () => {
    try {
      const res = await fetch(`/api/scenes/${sceneId}/history`)
      if (!res.ok) throw new Error('获取历史记录失败')
      const data = await res.json()
      setHistory(data)
    } catch (error) {
      setError('获取历史记录失败')
      console.error(error)
    } finally {
      setLoading(false)
    }
  }

  const handleExportHistory = async () => {
    try {
      const res = await fetch(`/api/scenes/${sceneId}/history/export`)
      if (!res.ok) throw new Error('导出失败')

      const blob = await res.blob()
      const url = URL.createObjectURL(blob)
      const link = document.createElement('a')
      link.href = url
      link.download = `场景_${sceneName}_执行历史_${format(new Date(), 'yyyyMMdd_HHmmss')}.csv`
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      URL.revokeObjectURL(url)

      toast.success('导出成功')
    } catch (error) {
      console.error('导出失败:', error)
      toast.error('导出失败')
    }
  }

  const handleRetry = async (historyId: string) => {
    try {
      const res = await fetch('/api/scenes/execute', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({ 
          sceneId,
          retryHistoryId: historyId 
        }),
      })

      if (!res.ok) throw new Error('重试失败')
      
      toast.success('已开始重试执行')
      // 延迟刷新列表，等待执行完成
      setTimeout(fetchHistory, 2000)
    } catch (error) {
      console.error('重试失败:', error)
      toast.error('重试失败')
    }
  }

  // 根据筛选条件过滤历史记录
  const filteredHistory = useMemo(() => {
    return history.filter(record => {
      // 状态筛选
      if (filters.status !== 'ALL' && record.status !== filters.status) {
        return false
      }

      // 时间范围筛选
      const recordDate = new Date(record.startTime)
      const now = new Date()
      if (filters.timeRange !== 'ALL') {
        const ranges = {
          TODAY: { start: new Date(now.setHours(0,0,0,0)), end: new Date() },
          WEEK: { start: subDays(now, 7), end: new Date() },
          MONTH: { start: subDays(now, 30), end: new Date() }
        }
        const range = ranges[filters.timeRange]
        if (!isWithinInterval(recordDate, range)) {
          return false
        }
      }

      // 搜索筛选
      if (filters.search) {
        const searchText = filters.search.toLowerCase()
        return (
          record.message?.toLowerCase().includes(searchText) ||
          record.actionLogs.some(log => 
            log.deviceName.toLowerCase().includes(searchText) ||
            log.message?.toLowerCase().includes(searchText)
          )
        )
      }

      return true
    })
  }, [history, filters])

  // 分页处理
  const paginatedHistory = useMemo(() => {
    const start = (page - 1) * itemsPerPage
    return filteredHistory.slice(start, start + itemsPerPage)
  }, [filteredHistory, page])

  const totalPages = Math.ceil(filteredHistory.length / itemsPerPage)

  if (loading) {
    return <div className="text-gray-500">加载中...</div>
  }

  if (error) {
    return <div className="text-red-500">{error}</div>
  }

  if (history.length === 0) {
    return <div className="text-gray-500">暂无执行记录</div>
  }

  return (
    <div>
      <div className="flex justify-between items-center mb-4">
        <h3 className="text-sm font-medium text-gray-700">执行历史记录</h3>
        <div className="flex space-x-2">
          <button
            onClick={handleExportHistory}
            className="px-3 py-1 text-sm bg-blue-100 text-blue-800 rounded-md hover:bg-blue-200"
          >
            导出CSV
          </button>
        </div>
      </div>

      <div className="space-y-4">
        {/* 筛选和搜索控件 */}
        <div className="flex flex-wrap gap-4 mb-4">
          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              状态
            </label>
            <select
              value={filters.status}
              onChange={(e) => setFilters(prev => ({ 
                ...prev, 
                status: e.target.value as FilterOptions['status']
              }))}
              className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500"
            >
              <option value="ALL">全部</option>
              <option value="SUCCESS">成功</option>
              <option value="FAILED">失败</option>
              <option value="PARTIAL_SUCCESS">部分成功</option>
            </select>
          </div>

          <div>
            <label className="block text-sm font-medium text-gray-700 mb-1">
              时间范围
            </label>
            <select
              value={filters.timeRange}
              onChange={(e) => setFilters(prev => ({ 
                ...prev, 
                timeRange: e.target.value as FilterOptions['timeRange']
              }))}
              className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500"
            >
              <option value="ALL">全部时间</option>
              <option value="TODAY">今天</option>
              <option value="WEEK">最近7天</option>
              <option value="MONTH">最近30天</option>
            </select>
          </div>

          <div className="flex-1">
            <label className="block text-sm font-medium text-gray-700 mb-1">
              搜索
            </label>
            <input
              type="text"
              value={filters.search}
              onChange={(e) => setFilters(prev => ({ 
                ...prev, 
                search: e.target.value 
              }))}
              placeholder="搜索设备名称或消息..."
              className="mt-1 block w-full rounded-md border-gray-300 shadow-sm focus:border-indigo-500 focus:ring-indigo-500"
            />
          </div>
        </div>

        {/* 历史记录列表 */}
        {paginatedHistory.length === 0 ? (
          <div className="text-center py-12">
            <p className="text-gray-500">没有找到匹配的记录</p>
          </div>
        ) : (
          <>
            <div className="space-y-4">
              {paginatedHistory.map(record => (
                <div
                  key={record.id}
                  className={`p-4 rounded-lg border ${
                    record.status === 'SUCCESS'
                      ? 'bg-green-50 border-green-200'
                      : record.status === 'PARTIAL_SUCCESS'
                      ? 'bg-yellow-50 border-yellow-200'
                      : 'bg-red-50 border-red-200'
                  }`}
                >
                  <div className="flex justify-between items-start">
                    <div>
                      <span
                        className={`inline-block px-2 py-1 text-xs rounded ${
                          record.status === 'SUCCESS'
                            ? 'bg-green-100 text-green-800'
                            : record.status === 'PARTIAL_SUCCESS'
                            ? 'bg-yellow-100 text-yellow-800'
                            : 'bg-red-100 text-red-800'
                        }`}
                      >
                        {record.status === 'SUCCESS' ? '执行成功' :
                         record.status === 'PARTIAL_SUCCESS' ? '部分成功' : 
                         '执行失败'}
                      </span>
                      {record.message && (
                        <p className="mt-1 text-sm text-gray-600">{record.message}</p>
                      )}
                    </div>
                    <time className="text-sm text-gray-500">
                      {format(record.startTime, 'yyyy-MM-dd HH:mm:ss')}
                    </time>
                  </div>

                  <div className="mt-2 text-sm text-gray-600">
                    <p>执行时长: {record.duration}ms</p>
                    <div className="mt-2">
                      <p className="font-medium">动作执行详情:</p>
                      <div className="mt-1 space-y-1">
                        {record.actionLogs.map((log, index) => (
                          <div
                            key={index}
                            className={`p-2 rounded ${
                              log.status === 'SUCCESS'
                                ? 'bg-green-50'
                                : 'bg-red-50'
                            }`}
                          >
                            <p>
                              {log.deviceName} - {log.actionType}: {log.value}
                              <span className="ml-2 text-xs">
                                ({log.duration}ms)
                              </span>
                            </p>
                            {log.message && (
                              <p className="text-xs text-red-600">{log.message}</p>
                            )}
                          </div>
                        ))}
                      </div>
                    </div>
                  </div>

                  {record.error && (
                    <div className="mt-2">
                      <button
                        onClick={() => console.log(record.error)}
                        className="text-sm text-red-600 hover:text-red-800"
                      >
                        查看错误详情
                      </button>
                    </div>
                  )}

                  <div className="mt-2 flex items-center space-x-4">
                    {record.status !== 'SUCCESS' && record.retryCount < 3 && (
                      <button
                        onClick={() => handleRetry(record.id)}
                        className="text-sm text-indigo-600 hover:text-indigo-800"
                      >
                        重试执行
                      </button>
                    )}
                    {record.retryCount > 0 && (
                      <span className="text-sm text-gray-500">
                        第 {record.retryCount} 次重试
                      </span>
                    )}
                    {record.retryOf && (
                      <span className="text-sm text-gray-500">
                        重试自: {record.retryOf}
                      </span>
                    )}
                  </div>
                </div>
              ))}
            </div>

            {/* 分页控件 */}
            <div className="flex justify-between items-center mt-4">
              <div className="text-sm text-gray-700">
                共 {filteredHistory.length} 条记录
              </div>
              <div className="flex space-x-2">
                <button
                  onClick={() => setPage(p => Math.max(1, p - 1))}
                  disabled={page === 1}
                  className={`px-3 py-1 rounded ${
                    page === 1
                      ? 'bg-gray-100 text-gray-400'
                      : 'bg-indigo-100 text-indigo-700 hover:bg-indigo-200'
                  }`}
                >
                  上一页
                </button>
                <span className="px-3 py-1">
                  {page} / {totalPages}
                </span>
                <button
                  onClick={() => setPage(p => Math.min(totalPages, p + 1))}
                  disabled={page === totalPages}
                  className={`px-3 py-1 rounded ${
                    page === totalPages
                      ? 'bg-gray-100 text-gray-400'
                      : 'bg-indigo-100 text-indigo-700 hover:bg-indigo-200'
                  }`}
                >
                  下一页
                </button>
              </div>
            </div>
          </>
        )}
      </div>
    </div>
  )
} 